package web;

import com.alibaba.fastjson2.JSONObject;
import dao.impl.StudentDaoImpl;
import domain.Student;
import service.IStudentService;
import service.impl.IStudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.SQLException;


/**
 * @author 于金鹏
 * @Date 2024/12/12 18:41
 * @Package yujinpeng
 */
@WebServlet("/delete")
public class DeleteStudent extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, IOException {
        // 一、获取请求信息
        // 解决乱码问题
        req.setCharacterEncoding("utf-8");
        // 解析请求体中的参数
        // 1. 获取输入流
        BufferedReader reader = req.getReader();
        // 2. 获取请求的完整信息
        StringBuilder requestBodyJsonStr = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            requestBodyJsonStr.append(line);
        }
        // 3. 将字符串信息解析成json对象
        Student student = JSONObject.parseObject(requestBodyJsonStr.toString(), Student.class);
        if (student == null) {
            student = new Student();
        }

        // 二、进行业务逻辑处理，执行删除操作
        IStudentService studentService = new IStudentServiceImpl(new StudentDaoImpl());
        int id = student.getId();
        try {
            studentService.deleteStudent(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        // 三、进行数据响应
        resp.setContentType("application/json;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().write(JSONObject.toJSONString(student));
    }
}

